﻿using Autofac;
using Curry.Forum.Command.Domain.Service;
using Curry.Forum.Command.Handler.AutoMapper.Map;
using Curry.Forum.Command.Handler.CommandHandler;
using Curry.Forum.Command.Repository;
using Curry.Forum.Query.Command;
using Curry.Forum.Query.Service.Dapper;
using System.Reflection;

namespace Curry.Forum.Command.Handler.AutoFac
{
    public class AutofacExt
    {
        private static IContainer _container;
        private static readonly ContainerBuilder _builder = new ContainerBuilder();

        public static void RegisterApplication()
        {
            _builder.RegisterType<MapRequest>().AsImplementedInterfaces();
            //_builder.RegisterType<MapResponse>().AsImplementedInterfaces();

            //注册handler
            _builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(ArticleHandler)));

            //注册Repository
            _builder.RegisterAssemblyTypes(typeof(ArticleRepo).Assembly)
                .Where(t => typeof(Curry.Forum.Command.Domain.IRepository.IDependency).IsAssignableFrom(t) && !t.IsAbstract)
                .AsImplementedInterfaces().InstancePerDependency();

            //注册AppService
            //_builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(ArticleCommandApp)));


            //注册领域服务
            _builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(ArticleService)))
                .Where(u => u.Namespace == "Curry.Forum.Command.Domain.Service");


            //查询部分

            //注册Repository
            _builder.RegisterAssemblyTypes(typeof(ArticleQueryService).Assembly)
                .Where(t => typeof(Curry.Forum.Query.Service.IDependency).IsAssignableFrom(t) && !t.IsAbstract)
                .AsImplementedInterfaces().InstancePerDependency();

            //注册command
            _builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(ArticleCommand)));

            _container = _builder.Build();
        }

        public static T GetFromFac<T>()
        {
            return _container.Resolve<T>();
        }

        /// <summary>
        /// 根据从容器中获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static T GetFromFacKey<T>(object num) where T : class
        {
            return _container.ResolveKeyed<T>(num);
        }
    }
}
